package com.yc;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
/**
 * @author zwei
 * @create 2024-07-19 9:40
 */
public class Test4_talkClient {
    private static Logger logger=Logger.getLogger(Test4_talkClient.class.getName());
    public static void main(String[] args) throws IOException {
        InetAddress inetAddress=InetAddress.getByName("localhost");
        System.out.println(inetAddress);
        Socket socket=new Socket(inetAddress,10001);
        logger.info("客户端连接服务器"+socket.getRemoteSocketAddress()+"成功");
        //客户端通过键盘录取信息
        try (Scanner scanner=new Scanner(System.in);
             //去、套接字流
             Scanner clientReader=new Scanner(socket.getInputStream());
             PrintWriter printWriter=new PrintWriter(socket.getOutputStream())
        ){
            do{
                System.out.println("请输入客户端想对服务器说的话：");
                String line=scanner.nextLine();
                //套接字提供的输出流
                printWriter.println(line);
                printWriter.flush();
                if ("bye".equalsIgnoreCase(line)){
                    System.out.println("客户端主动断开与服务器的连接。。。");
                    break;
                }
                String response=clientReader.nextLine();
                System.out.println("服务器对客户端说："+response);
                if ("bye".equalsIgnoreCase(response)){
                    System.out.println("服务器主动断开与客户端的连接。。。");
                    break;
                }
            }while (true);
            System.out.println("在客户端正常结束聊天。。。");
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("客户端关闭。。。");
    }
}
